package management_system;

import java.io.*;
import java.util.*;

public class FileUtil {

    /* ============== 1. 写 CSV：0.00 → 写 "null" ============== */
    public static void saveToCsv(List<Student> students, String path) throws IOException {
        String[] courseOrder = {"高等数学", "大学英语", "Java程序设计"};
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "GBK"))) {
            bw.write("学号,姓名,GPA," + join(courseOrder, ","));
            bw.newLine();
            for (Student stu : students) {
                StringBuilder sb = new StringBuilder();
                sb.append(stu.getId()).append(',')
                        .append(stu.getName()).append(',');

                /* 核心：0 且无成绩 → null */
                boolean allNull = Arrays.stream(courseOrder)
                        .allMatch(cn -> stu.getScoreByCourseName(cn) == null);
                double gpa = stu.getGPA();
                sb.append(allNull ? "null" : String.format("%.2f", gpa));

                /* 各门成绩 */
                for (String cn : courseOrder) {
                    Score sc = stu.getScoreByCourseName(cn);
                    sb.append(',').append(sc == null ? "null" : String.valueOf(sc.getScore()));
                }
                bw.write(sb.toString());
                bw.newLine();
            }
        }
    }

    /* ============== 读 CSV：跳过 null，统计有效人数 ============== */
    public static Map<String, Object> readFromCsv(String path) throws IOException {
        String[] courseOrder = {"高等数学", "大学英语", "Java程序设计"};
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GBK"))) {
            br.readLine();
            List<Student> students = new ArrayList<>();
            double totalGpa = 0;
            int validCount = 0;                       // 有效人数
            String line;
            while ((line = br.readLine()) != null) {
                String[] arr = line.split(",", -1);
                if (arr.length < 6) continue;
                String id = arr[0], name = arr[1];
                Student stu = new Student(id, name);
                boolean hasValid = false;             // 本行是否有有效成绩

                for (int j = 0; j < courseOrder.length; j++) {
                    String val = arr[j + 3].trim();
                    if (val.equals("null") || val.isEmpty()) continue;
                    double score = Double.parseDouble(val);
                    Course course = new Course("C" + (j + 1), courseOrder[j],
                            j == 0 ? 4 : j == 1 ? 3 : 3);
                    try {
                        stu.addScore(new Score(course, score));
                        hasValid = true;              // 标记有效
                    } catch (InvalidScoreException e) {
                        System.out.println(id + "学号成绩异常：" + e.getMessage());
                    }
                }
                students.add(stu);
                if (hasValid) {                       // 只有有效才累加
                    totalGpa += stu.getGPA();
                    validCount++;
                }
            }
            double classAvg = validCount == 0 ? 0 : totalGpa / validCount;
            Map<String, Object> res = new HashMap<>();
            res.put("students", students);
            res.put("classAvg", classAvg);
            res.put("validCount", validCount);        // 返回有效人数
            return res;
        }
    }

    /* ============== 写 TXT：用有效人数计算，全无效 → 写 "null" ============== */
    public static void writeTxt(String path, List<Student> students, double classAvg, int validCount) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "utf-8"))) {
            bw.write(validCount == 0 ? "班级平均 GPA：null" : "班级平均 GPA：" + String.format("%.2f", classAvg));
            bw.newLine();
        }
    }

    //join
    private static String join(String[] arr, String sep) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if (i > 0) sb.append(sep);
            sb.append(arr[i]);
        }
        return sb.toString();
    }
}